package cn.imu.appdevexperiment2020.utils;

import org.json.JSONObject;

import java.util.Map;

import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class HttpUtil {
    public static final String ADDR = "http://43.138.21.29:8010";

    public static void post(String url, Map<String, String> map, Callback callback) {
        //添加鉴权参数
        Map<String, String> mapParams = AuthUtil.GetAuth();
        //获取当前时间戳
        String token = "";
        try {
            token = mapParams.get(AuthConstants.TOKEN);
        } catch (Exception e) {
        }
        if (url.contains("?"))
            url = url + "&appId=" + mapParams.get(AuthConstants.APP_ID) + "&timeStamp=" + mapParams.get(AuthConstants.TIME_STAMP) + "&token=" + token;
        else
            url = url + "?appId=" + mapParams.get(AuthConstants.APP_ID) + "&timeStamp=" + mapParams.get(AuthConstants.TIME_STAMP) + "&token=" + token;
        //由map创建jsonObject，用于给请求体添加参数
        JSONObject jsonObject = new JSONObject(map);
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        //从jsonObject创建请求体
        RequestBody body = RequestBody.create(JSON, jsonObject.toString());
        final Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        OkHttpClient client = new OkHttpClient();
        client.newCall(request).enqueue(callback);
    }

    public static void get(String url, Callback callback) {
        //添加鉴权参数
        Map<String, String> mapParams = AuthUtil.GetAuth();
        String token = mapParams.get(AuthConstants.TOKEN);

        if (url.contains("?"))
            url = url + "&appId=" + mapParams.get(AuthConstants.APP_ID) + "&timeStamp=" + mapParams.get(AuthConstants.TIME_STAMP) + "&token=" + token;
        else
            url = url + "?appId=" + mapParams.get(AuthConstants.APP_ID) + "&timeStamp=" + mapParams.get(AuthConstants.TIME_STAMP) + "&token=" + token;
        //创建请求体，类型为application/json
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), "");
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        OkHttpClient client = new OkHttpClient();
        //使用异步方式发送请求
        client.newCall(request).enqueue(callback);
    }

}
